import React, { useEffect, useState } from 'react'
import { Ajax } from '../../api/api'
import MyHead from '../../components/MyHead'
import { useParams, useNavigate } from 'react-router-dom';
import './index.scss'
import { List, Stepper, Button, Badge, Dialog, Popup, Input, TextArea, Ellipsis, Empty, Image } from 'antd-mobile'
import { AntOutline, FillinOutline, HeartOutline, StarOutline, StarFill, HeartFill, CouponOutline, DeleteOutline, TruckOutline } from 'antd-mobile-icons'
import { useSelector, useDispatch } from 'react-redux';
import { ShowMsg } from '../../utils/message';
import { getCartListAsync } from '../../rtk/modules/data';
import { useTimeout } from 'ahooks';
import { baseURL } from '../../api/request';
import moment from 'moment';


const Good = () => {
    const defaultImg = ''
    const router = useNavigate()
    const userInfo = useSelector((state: any) => state.data.userInfo)
    const cartList = useSelector((state: any) => state.data.cartList)
    const dispatch = useDispatch() as any;
    const [data, setData] = useState<any>(null)
    const [value, setValue] = useState<number>(1)
    const [likeCount, setLikeCount] = useState<number>(0)
    const [collectCount, setCollectCount] = useState<number>(0)

    const [hasLike, setHasLike] = useState<boolean>(false)
    const [hasCollect, setHasCollect] = useState<boolean>(false)

    const [comments, setComments] = useState<any>([])
    const params = useParams()
    const [show, setShow] = useState<boolean>(false)
    const [title, setTitle] = useState<any>('')
    const getgoodonedata = async () => {
        let res: any = await Ajax.getgoodone({
            id: params.id
        })
        if (res.code == 200) {
            setData(res.result)
        }
    }


    const todoCheckLogin = (next: any) => {
        if (userInfo) {
            next()
        } else {
            Dialog.show({
                content: '你尚未登录,请先去登录!',
                closeOnAction: true,
                actions: [
                    [
                        {
                            key: 'cancel',
                            text: '取消',
                        },
                        {
                            key: 'delete',
                            text: '确定',
                            bold: true,
                            danger: true,
                            onClick: () => {
                                router('/login')
                            }
                        },
                    ],
                ],
            })
        }
    }

    const gotoPay = () => {
        todoCheckLogin(() => {
            router('/pay?total=' + data.price * value * data.discount / 10)
        })
    }

    const addToCart = () => {
        todoCheckLogin(async () => {
            let res: any = await Ajax.addtocart({
                goodId: params.id,
                good: data,
                count: value
            })
            if (res.code == 200) {

                ShowMsg(res.msg)
                setTimeout(() => {
                    dispatch(getCartListAsync({}))
                }, 500)
            }
        })
    }

    const getDataByPhone = async () => {
        let res = await Ajax.getlikesdatabyphone({
            goodId: params.id,
            hasLike: 1
        }) as any

        let res2 = await Ajax.getlikesdatabyphone({
            goodId: params.id,
            hasCollect: 1
        }) as any

        setHasLike(!!res.result.length)
        setHasCollect(!!res2.result.length)
    }

    const getLikeData = async () => {
        let res = await Ajax.getlikesdata({
            goodId: params.id,
            hasLike: 1
        }) as any;

        let res2 = await Ajax.getlikesdata({
            goodId: params.id,
            hasCollect: 1
        }) as any;
        setLikeCount(res.result.length)
        setCollectCount(res2.result.length)
    }

    const todoLike = () => {
        todoCheckLogin(async () => {
            let res = await Ajax.getlikesdatabyphone({
                goodId: params.id,
                hasLike: 1
            }) as any
            var item = res.result[0]
            if (res.result.length > 0) {
                let res2: any = await Ajax.deletelikes({
                    _id: item._id
                })
                if (res2.code == 200) {
                    ShowMsg('你取消了点赞')
                    setLikeCount(likeCount - 1)
                    setHasLike(false)
                }
            } else {
                let res2: any = await Ajax.addlikes({
                    goodId: params.id,
                    hasLike: 1,
                    phone: userInfo.phone,
                    good: data
                })
                if (res2.code == 200) {
                    ShowMsg('点赞成功')
                    setLikeCount(likeCount + 1)
                    setHasLike(true)
                }
            }
        })
    }

    const todoCollect = () => {
        todoCheckLogin(async () => {
            let res = await Ajax.getlikesdatabyphone({
                goodId: params.id,
                hasCollect: 1
            }) as any
            var item = res.result[0]
            if (res.result.length > 0) {
                let res2: any = await Ajax.deletelikes({
                    _id: item._id
                })
                if (res2.code == 200) {
                    ShowMsg('你取消了收藏')
                    setCollectCount(collectCount - 1)
                    setHasCollect(false)
                }
            } else {
                let res2: any = await Ajax.addlikes({
                    goodId: params.id,
                    hasCollect: 1,
                    phone: userInfo.phone,
                    good: data
                })
                if (res2.code == 200) {
                    ShowMsg('收藏成功')
                    setCollectCount(collectCount + 1)
                    setHasCollect(true)
                }
            }
        })
    }

    const getCommentData = async () => {
        let res = await Ajax.getcomments({
            goodId: params.id,
        }) as any;
        setComments(res.result)
    }

    const addComment = () => {
        todoCheckLogin(async () => {
            if (title) {
                let res = await Ajax.addcoments({
                    userInfo: userInfo,
                    phone: userInfo.phone,
                    title,
                    good: data,
                    goodId: params.id
                }) as any;
                if (res.code == 200) {
                    ShowMsg('评论成功')
                    setTitle('')
                    getCommentData()

                }
            } else {
                ShowMsg("请先输入评论的内容")
            }
        })
    }

    const deleteOne = async (item: any, index: any) => {
        let res = await Ajax.deletecoment({
            _id: item._id
        }) as any;
        if (res.code == 200) {
            ShowMsg('删除成功')
            getCommentData()
        }
    }
    useEffect(() => {
        getgoodonedata()
        getLikeData()

        getCommentData()

        if (userInfo) {
            dispatch(getCartListAsync({}))
            getDataByPhone()

        }
    }, [dispatch])


    return (
        data && <div className='pg good'>
            <MyHead title={data.name} />
            <div className="boxdata">
                <img src={data.img} alt="" className='gimg' />
            </div>
            <List mode='card' header='商品信息'>
                <List.Item extra={data.type.text} >
                    分类
                </List.Item>
                <List.Item extra={data.discount + '折'} >
                    折扣
                </List.Item>
                <List.Item extra={data.price} >
                    原价
                </List.Item>
                <List.Item extra={data.price * data.discount / 10} >
                    单价(元)
                </List.Item>
                <List.Item extra={<Stepper
                    min={0}
                    value={value}
                    onChange={setValue}
                />} >
                    购买数量
                </List.Item>
                <List.Item extra={data.price * value * data.discount / 10}  >
                    小计(元)
                </List.Item>
            </List>

            <div className="good-foot">
                <div className="fbox" onClick={() => setShow(true)}>
                    <Badge content={comments.length} >
                        <FillinOutline className='ficon' />
                    </Badge>
                    <span >评论</span>
                </div>
                <div className="fbox" onClick={todoLike} >
                    <Badge content={likeCount} >
                        {
                            hasLike ? <HeartFill className='ficon' style={{ color: "#f50" }} /> : <HeartOutline className='ficon' />
                        }
                    </Badge>
                    <span style={{ color: hasLike ? '#f50' : '#666' }}>
                        {hasLike ? '已点赞' : '点赞'}
                    </span>
                </div>
                <div className="fbox" onClick={todoCollect}>
                    <Badge content={collectCount}  >

                        {
                            hasCollect ? <StarFill className='ficon' style={{ color: "#f50" }} /> : <StarOutline className='ficon' />
                        }
                    </Badge>
                    <span style={{ color: hasCollect ? '#f50' : '#666' }}>{hasCollect ? '已收藏' : '收藏'}</span>
                </div>
                <div className="fbox" onClick={() => router('/app/cart')}>
                    <Badge content={cartList.length} >
                        <TruckOutline className='ficon' />
                    </Badge>
                    <span>购物车</span>
                </div>
                <div className="btns">
                    <div className="fbtn">
                        <Button className="btn" onClick={addToCart} size='mini' color="success">加入购物车</Button>
                    </div>
                    <div className="fbtn">
                        <Button onClick={gotoPay} className="btn" size='mini' color="warning">立即购买</Button>
                    </div>
                </div>
            </div>


            <Popup
                visible={show}
                onMaskClick={() => {
                    setShow(false)
                }}
                bodyStyle={{
                    borderTopLeftRadius: '48px',
                    borderTopRightRadius: '48px',
                    minHeight: '80vh',
                }}
            >
                <div>
                    <h3 className="title" style={{ textAlign: 'center', padding: 30, fontSize: 48 }}>商品评论</h3>

                    <div className="input-box pd10" >
                        <TextArea
                            placeholder='请输入评论内容'
                            value={title}
                            onChange={val => {
                                setTitle(val)
                            }}
                            showCount
                            maxLength={200}
                            rows={3}
                            style={{ border: '1px solid #ddd', padding: 15, borderRadius: 20 }}
                        />
                        <Button onClick={addComment} color="warning" block className='mt10'>发表评论</Button>
                    </div>
                    <div className="cmtlist" style={{ height: '50vh', overflow: 'auto' }}>
                        {
                            comments.length > 0 ? <div>
                                <List header={'用户评论'}  >
                                    {comments.map((item: any, index: number) => (
                                        <List.Item
                                            key={item._id}
                                            prefix={
                                                <Image
                                                    src={item.userInfo.avatar ? item.userInfo.avatar.replace(/public/, baseURL) : defaultImg}
                                                    style={{ borderRadius: 20 }}
                                                    fit='cover'
                                                    width={90}
                                                    height={90}
                                                />
                                            }
                                            description={
                                                <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                                                    <span>{item.userInfo.username} </span>
                                                    <span>{moment(item.time).format('YYYY-MM-DD HH:mm')} </span>
                                                </div>
                                            }
                                        >
                                            {
                                                item.title
                                            }
                                            {
                                                item.userInfo.username == userInfo.username && <DeleteOutline onClick={() => deleteOne(item, index)} className='ml10' />
                                            }
                                        </List.Item>
                                    ))}
                                </List>
                            </div>
                                :
                                <div className="empty">
                                    <Empty
                                        style={{ padding: '64px 0' }}
                                        description='暂无评论'
                                    />
                                </div>
                        }
                    </div>
                </div>
            </Popup>
        </div>
    )
}

export default Good